package cn.kys.modules.monitor.service.impl;

import cn.kys.common.utils.StringUtils;
import cn.kys.logging.repository.LogRepository;
import cn.kys.modules.monitor.domain.Visits;
import cn.kys.modules.monitor.repository.VisitsRepository;
import cn.kys.modules.monitor.service.VisitsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**功能描述：后台首页统计业务接口实现
 * @Auther:http://www.kys.cn
 * @Date:2020/4/1
 * @Description:cn.kys.modules.monitor.service.impl
 * @version:1.0
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class VisitsServiceImpl implements VisitsService {

    private final VisitsRepository visitsRepository;

    private final LogRepository logRepository;

    public VisitsServiceImpl(VisitsRepository visitsRepository, LogRepository logRepository) {
        this.visitsRepository = visitsRepository;
        this.logRepository = logRepository;
    }

    /**
     * 提供给定时任务，每天0点执行
     */
    @Override
    public void save() {
        LocalDate localDate = LocalDate.now();
        Visits visits = visitsRepository.findByDate(localDate.toString());
        if(visits == null){
            visits = new Visits();
            visits.setWeekDay(StringUtils.getWeekDay());
            visits.setPvCounts(1L);
            visits.setIpCounts(1L);
            visits.setDate(localDate.toString());
            //visitsRepository.save(visits);
        }
    }

    /**
     * 获取数据
     * @return
     */
    @Override
    public Object get() {
        Map<String,Object> map = new HashMap<>(4);
        LocalDate localDate = LocalDate.now();
        Visits visits = visitsRepository.findByDate(localDate.toString());
        List<Visits> list = visitsRepository.findAllVisits(strToSqlDate(localDate.minusDays(6).toString()),strToSqlDate(localDate.plusDays(1).toString()));

        long recentVisits = 0, recentIp = 0;
        for (Visits data : list) {
            recentVisits += data.getPvCounts();
            recentIp += data.getIpCounts();
        }
        //日流量
        map.put("newVisits",visits==null?0:visits.getPvCounts());
        //日IP量
        map.put("newIp",visits==null?0:visits.getIpCounts());
        //周流量
        map.put("recentVisits",recentVisits);
        //周IP量
        map.put("recentIp",recentIp);
        return map;
    }

    /**
     * 新增统计数据到数据表
     * @param request /
     */
    @Override
    public void count(HttpServletRequest request) {
        LocalDate localDate = LocalDate.now();
        Visits visits = visitsRepository.findByDate(localDate.toString());
        visits.setPvCounts(visits.getPvCounts()+1);
        long ipCounts = logRepository.findIp(strToSqlDate(localDate.toString()), strToSqlDate(localDate.plusDays(1).toString()));
        visits.setIpCounts(ipCounts);
        visitsRepository.save(visits);
    }

    /**
     * 获取图表数据
     * @return
     */
    @Override
    public Object getChartData() {
        Map<String,Object> map = new HashMap<>(3);
        LocalDate localDate = LocalDate.now();
        List<Visits> list = visitsRepository.findAllVisits(strToSqlDate(localDate.minusDays(6).toString()),strToSqlDate(localDate.plusDays(1).toString()));
        map.put("weekDays",list.stream().map(Visits::getWeekDay).collect(Collectors.toList()));
        map.put("visitsData",list.stream().map(Visits::getPvCounts).collect(Collectors.toList()));
        map.put("ipData",list.stream().map(Visits::getIpCounts).collect(Collectors.toList()));
        return map;
    }

    /**
     * 获取地图图表数据
     * @return
     */
    @Override
    public Object getMapChartData() {
        Map<String,Object> map = new HashMap<>(3);
        List<Map> list = visitsRepository.findVisitsMonthDataByProvince();
        map.put("visitsData",list);
        return map;
    }

    /**
     * 将String字符串转换为java.sql.Timestamp格式日期,用于数据库保存
     * @param strDate
     *            表示日期的字符串
     * @param dateFormat
     *            传入字符串的日期表示格式（如："yyyy-MM-dd HH:mm:ss"）
     * @return java.sql.Timestamp类型日期对象（如果转换失败则返回null）
     */
    public static java.sql.Timestamp strToSqlDate(String strDate) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date = null;
        try {
            date = sf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        java.sql.Timestamp dateSQL = new java.sql.Timestamp(date.getTime());
        return dateSQL;
    }
}
